package com.ysxsoft.wdg.ui.activity.home;

import android.Manifest;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.classic.common.MultipleStatusView;
import com.google.android.exoplayer2.extractor.ts.AdtsReader;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.home.LocationAdapter;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BannerBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.bean.response.PinOrderResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.util.transform.FastSpeedLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static android.view.View.GONE;
import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.LOCATION_UP;

public class LocationActivity extends BaseActivity {


    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_tv_r)
    TextView titleTvR;
    @BindView(R.id.title_content)
    EditText etContent;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.searchRecyclerView)
    RecyclerView searchRecyclerView;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private LocationAdapter mAdapter;
    private String address = "";
    private List<BannerBean> data = new ArrayList<>();

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tvLocation.setText(address);
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_location;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        etContent.setHint("请输入城市名称");

        tvLocation.setText("定位中...");
        titleTvR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSearch(data);
            }
        });

        recyclerview.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        mAdapter = new LocationAdapter(R.layout.item_his_text);
        recyclerview.setAdapter(mAdapter);

        initLocation();

        mApiHelper.getHotCity(new Observer<BaseBean<List<BannerBean>>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<List<BannerBean>> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    data.addAll(baseBean.getData());
                    mAdapter.setNewData(baseBean.getData());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });


    }

    @Override
    protected void setListener() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                EventBus.getDefault().post(new CommentEvent(LOCATION_UP));
                SharePrefUtils.saveAddress(mAdapter.getItem(position).getName());
                finish();
            }
        });
    }


    @OnClick({R.id.title_finish, R.id.tv_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                //隐藏搜索列表
                if (multStatusView.getVisibility() == View.VISIBLE) {
                    etContent.setText("");
                    multStatusView.setVisibility(GONE);
                    return;
                }
                finish();
                break;
            case R.id.tv_location:
                break;
        }
    }

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    EventBus.getDefault().post(new CommentEvent(LOCATION_UP));
                    address = amapLocation.getCity().replace("市", "");
                    handler.sendEmptyMessageDelayed(0, 2000);
                    //可在其中解析amapLocation获取相应内容。
                    SharePrefUtils.saveLatitude(amapLocation.getLatitude() + "");
                    SharePrefUtils.saveLongitude(amapLocation.getLongitude() + "");
                    SharePrefUtils.saveAddress(address);
                    KLog.e("Latitude=" + amapLocation.getLatitude() + ",Longitude=" + amapLocation.getLongitude());
                } else {
                    address = "定位失败";
                    handler.sendEmptyMessageDelayed(0, 2000);
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    KLog.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);


        new RxPermissions(this)
                .request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) {
                        //启动定位
                        mLocationClient.startLocation();
                    }
                });
    }

    @Override
    protected void onStop() {
        super.onStop();
        handler.removeMessages(0);
    }

    ///////////////////////////////////////////////////////////////////////////
    // 城市搜索
    //////////////////////////////////////////////////////////////////////////
    private CustomSearchAdapter adapter;

    private void showSearch(List<BannerBean> data) {
        String keyword = etContent.getText().toString();
        if ("".equals(keyword)) {
            return;
        }
        List<BannerBean> d = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            BannerBean bannerBean = data.get(i);
            if (bannerBean.getName()!=null&&bannerBean.getName().contains(keyword)) {
                d.add(bannerBean);
            }
        }
        if (adapter == null) {
            adapter = new CustomSearchAdapter(R.layout.item_his_text);
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    BannerBean bannerBean = (BannerBean) adapter.getItem(position);
                    EventBus.getDefault().post(new CommentEvent(LOCATION_UP));
                    SharePrefUtils.saveAddress(bannerBean.getName());
                    finish();
                }
            });
            searchRecyclerView.setLayoutManager(new FastSpeedLinearLayoutManager(LocationActivity.this));
            searchRecyclerView.addItemDecoration(new DividerItemDecoration(LocationActivity.this,DividerItemDecoration.VERTICAL));
            searchRecyclerView.setAdapter(adapter);
        }
        if (d.isEmpty()) {
            multStatusView.showEmpty();
        } else {
            multStatusView.showContent();
        }
        adapter.setNewData(d);
        multStatusView.setVisibility(View.VISIBLE);
    }

    /**
     * 商品
     */
    private class CustomSearchAdapter extends BaseQuickAdapter<BannerBean, BaseViewHolder> {
        public CustomSearchAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, BannerBean item) {
            helper.setText(R.id.tv_content, item.getName());
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && multStatusView.getVisibility() == View.VISIBLE) {
            multStatusView.setVisibility(GONE);
            etContent.setText("");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
